%%%-------------------------------------------------------------------
%%% @author wukai
%%% @copyright (C) 2017, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 17. 十一月 2017 14:01
%%%-------------------------------------------------------------------
-module(okmqtt_topic).
-author("wukai").

%% API
-export([topic_check/3, verify/1,qos_check/1,fix/1]).

topic_check(_, Topic,_)when byte_size(Topic) == 0->false;
topic_check(Type, Topic,Level) ->
  Str = binary_to_list(Topic),
  Len = length(Str),
  {_, Mp} = check_rule(Type,Level),
  case re:run(Str, Mp) of
    {match, [{0, Len} | _]} -> true;
    nomatch -> false
  end.


qos_check(0)->true;
qos_check(1)->true;
qos_check(2)->true;
qos_check(_)->false.

%%带通配符的规则校验
check_rule(sub,willcard) -> re:compile("^((?<!/)/[^\\+#\$]*|(?<=/)\\+|^(?<!\\+)\\+/|(?<=/)#(?=$)|^[^/#\\+]{1,}|^\\+$|^#$){1,}$");
%%不带通配符的规则校验
check_rule(sub,_) -> re:compile("^\\$?[^#\\+\\$/]*(/[^#\\+\\$/]*)*$");
check_rule(pub,_) -> re:compile("^[^#\\+\\$/]*(/[^#\\+\\$/]*)*$").

%%单个#过滤器
verify("#") -> true;
verify("/#") -> true;
%%单个+号的主题过滤器
verify("+/") -> true;
%%单个过滤器
verify("+/+") -> true;
verify("+") -> true.
fix(Filter) ->
  A1 = re:replace(binary_to_list(Filter), "\\+", "[^/#+]*"),
  A2 = re:replace(A1, "#", ".*"),
  A3 = re:replace(A2, "\\$", "\\\\$", [global, {return, list}]),
  {_, Mp} = re:compile(A3), Mp.


